<template>
  <h1>发微博页面</h1>
  <el-input placeholder="说点儿什么..." v-model="weibo.content"></el-input>
  <!--   上传组件开始 action:设置上传地址  name:设置参数名  limit:设置上传文件的熟练-->
  <el-upload name="file" :limit="1"
      v-model:file-list="fileList"
      action="http://localhost:8080/v1/upload"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
  >
    <el-icon><Plus /></el-icon>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
  <!--   上传组件结束   -->

  <el-button @click="post()">发布</el-button>
</template>

<script setup>
import {ref} from "vue";
import axios from "axios";
import qs from "qs";
import {ElMessage} from "element-plus";
import router from "@/router";

/*上传组件开始*/
const fileList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  //发出删除文件的请求
  axios.post('http://localhost:8080/v1/remove?imgUrl='+uploadFile.response.data)
  .then((response)=>{
    if (response.data.code==2001){
      ElMessage.success("服务器文件删除完成!");
    }
  })
}
const handlePictureCardPreview = (uploadFile) => {

  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
/*上传组件结束*/




const weibo = ref({content:""});
const post = ()=>{
    //得到上传文件的路径
  if (fileList.value.length==0){
    ElMessage.error("请选择上传的图片文件!");
    return;
  }
  let file = fileList.value[0];
  // file.response 服务器响应的内容(JsonResult)
  // ElMessage.success(file.response.data);
  //把上传成功的图片路径装进weibo对象中, 提交给服务器
  weibo.value.imgUrl = file.response.data;

  let user = localStorage.user?JSON.parse(localStorage.user):null;
  //给微博对象赋值作者的id
  weibo.value.userId = user.id;
  let data = qs.stringify(weibo.value);
  //发出请求
  axios.post('http://localhost:8080/v1/weibos/add-new',data)
  .then((response)=>{
    if (response.data.code==2001){
      ElMessage.success("发布完成!");
      router.push('/');//回到首页
    }else{ElMessage.error(response.data.msg);}
  })
}
</script>

<style scoped>

</style>